package com.example.javadbdemo.slice;

import com.example.javadbdemo.ResourceTable;
import com.example.javadbdemo.entity.Product;
import ohos.aafwk.ability.AbilitySlice;

import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.DatabaseHelper;
import ohos.data.rdb.*;
import ohos.data.resultset.ResultSet;

import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.List;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Button rdbQuery,rdbInsert,rdbDelete,rdbUpdata;
    private Text show;
    private TextField tf_name,tf_price;
    private static final HiLogLabel LOG_LABLE = new HiLogLabel(HiLog.LOG_APP, 0, "===DBdemo===");
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
        initListener();
    }
    private void initView(){
        tf_name=(TextField)findComponentById(ResourceTable.Id_tf_pname);
        tf_price=(TextField)findComponentById(ResourceTable.Id_tf_price);
        show=(Text)findComponentById(ResourceTable.Id_show);
        rdbInsert = (Button) findComponentById(ResourceTable.Id_rdb_insert);
        rdbDelete = (Button) findComponentById(ResourceTable.Id_rdb_delete);
        rdbUpdata = (Button) findComponentById(ResourceTable.Id_rdb_update);
        rdbQuery = (Button) findComponentById(ResourceTable.Id_rdb_query);

    }
    private void initListener() {

        rdbInsert.setClickedListener(this);
        rdbDelete.setClickedListener(this);
        rdbUpdata.setClickedListener(this);
        rdbQuery.setClickedListener(this);
    }
    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();
        switch (id) {

            case ResourceTable.Id_rdb_insert:
                if (tf_name.getText().equals("") && tf_price.getText().equals("")){
                    new ToastDialog(getContext())
                            .setText("输入框不能为空！")
                            .show();
                }else {
                    rdbInsert(new Product(tf_name.getText().toString(),Double.parseDouble(tf_price.getText().toString())));
                }
                break;
            case ResourceTable.Id_rdb_delete:
                rdbDelete();
                break;
            case ResourceTable.Id_rdb_update:
                rdbUpdata();
                break;
            case ResourceTable.Id_rdb_query:
                List<Product> productList=rdbQuery();
                if(productList.size()>0){
                    show.setText("");
                    for(Product product:productList) {
                        show.append(" " + product.getId() + "\t\t\t\t\t" + product.getProductName() +
                                "\t\t\t\t\t" + product.getPrice() + "\n");
                    }
                }else{
                    show.setText("暂无数据");
                }
                break;
        }
    }
        /**
         * 创建关系型数据库
         */
        private RdbStore rdbCreateDb() {
            StoreConfig config = StoreConfig.newDefaultConfig("test.db");
            DatabaseHelper helper = new DatabaseHelper(getContext());
            RdbStore rdbStore = helper.getRdbStore(config, 1, new RdbOpenCallback() {
                @Override
                public void onCreate(RdbStore rdbStore) {
                    //创建数据表
                    rdbStore.executeSql("create table if not exists tbl_product(id integer primary key autoincrement,productName text,price double)");
                    rdbStore.executeSql("insert into tbl_product values(1,'test',30)");
                }

                @Override
                public void onUpgrade(RdbStore rdbStore, int i, int i1) {
                    //升级数据库
                }
            });
            return rdbStore;
        }
        /**
         * 更新关系型数据库数据
         */
        private void rdbUpdata() {
            RdbPredicates rdbPredicates = new RdbPredicates("tbl_product").equalTo("id",1);
            ValuesBucket values = new ValuesBucket();
            values.putDouble("price",60.0);
            //更新数据
           int i= rdbCreateDb().update(values,rdbPredicates);
           if(i>0){
               new ToastDialog(getContext())
                       .setText("更新数据成功！")
                       .show();
           }
            //查询数据是否更新完成
            rdbQuery();
        }

        /**
         * 删除关系型数据库数据
         */
        private void rdbDelete() {
            RdbPredicates rdbPredicates = new RdbPredicates("tbl_product").equalTo("id",2);
            int i = rdbCreateDb().delete(rdbPredicates);
            if(i>0){
                new ToastDialog(getContext())
                        .setText("删除了第2条的数据成功！")
                        .show();
                HiLog.info(LOG_LABLE,"删除关系型数据库数据成功！删除了第2条的数据！");
            }


        }

        /**
         * 插入关系型数据库数据
         */
        private void rdbInsert(Product product) {
            //使用键值对方式插入数据库rdbCreateDb()获取的就是创建的时候生成的rdbStore
            ValuesBucket values = new ValuesBucket();

            values.putString("productName",product.getProductName());
            values.putDouble("price",product.getPrice());
            long id = rdbCreateDb().insert("tbl_product",values);
            if (id > 0){
                new ToastDialog(getContext())
                        .setText("插入数据成功！")
                        .show();
                HiLog.info(LOG_LABLE, "插入关系型数据库成功！");
            }else{
                new ToastDialog(getContext())
                        .setText("插入数据失败！")
                        .show();
                HiLog.info(LOG_LABLE, "插入关系型数据库失败,应该是已存在有相同userid的数据了");
            }

        }
        /**
         * 查询关系型数据库数据
         */
        private List<Product> rdbQuery() {
            List<Product> result = new ArrayList<>();

            String[] columns = new String[]{"id","productName","price"};
            RdbPredicates rdbPredicates = new RdbPredicates("tbl_product");
            ResultSet resultSet = rdbCreateDb().query(rdbPredicates,columns);
            while (resultSet.goToNextRow()){
                int pid = resultSet.getInt(resultSet.getColumnIndexForName("id"));
                String productName = resultSet.getString(resultSet.getColumnIndexForName("productName"));
                Double price= resultSet.getDouble(resultSet.getColumnIndexForName("price"));
                Product user = new Product(pid,productName,price);
                result.add(user);
                HiLog.info(LOG_LABLE, "查询到id=" + pid +"  productName=" +productName);
            }
            return result;
        }
}
